Vue.component("yl-button", {
  template: `
    <span>
        <el-button :type="type" @click="Export" :loading="loading">
            <slot></slot>
        </el-button>
        <el-table id="ExportData" :data="data" style="display: none; width: 100%;margin-bottom: 20px;">
        <el-table-column align="center" type="index" label="序号" width="50"></el-table-column>
        <el-table-column align="center" prop="Member_SerialNumber" width="140" show-overflow-tooltip label="下单人手机号"></el-table-column>
        <el-table-column align="center" prop="Member_Name" width="140" show-overflow-tooltip label="下单人姓名"></el-table-column>
        <el-table-column align="center" prop="Article_Name" width="250" show-overflow-tooltip label="购买过的商品"></el-table-column>
        <el-table-column align="center" prop="Activity_Name" width="250" show-overflow-tooltip  label="参与过的活动"></el-table-column>
        <el-table-column align="center" prop="Number" show-overflow-tooltip  label="有效下单次数"></el-table-column>
        <el-table-column align="center" prop="Quantity" show-overflow-tooltip label="购买商品数量"></el-table-column>
        <el-table-column align="center" prop="Sales_Amount" show-overflow-tooltip label="消费总额">
            <template v-slot="{row}">
                {{thousands(row.Sales_Amount)}}
            </template>
        </el-table-column>
        <el-table-column align="center" prop="Reality_Amount" show-overflow-tooltip label="实收总额">
            <template v-slot="{row}">
                {{thousands(row.Reality_Amount)}}
            </template>
        </el-table-column>
        <el-table-column align="center" prop="Sales_Point" show-overflow-tooltip label="使用积分总计"></el-table-column>
        </el-table>
    </span>`,
  props: ["loading", "data", "type"],
  methods: {
    Export() {
      this.$emit("click");
    },
  },
});
Vue.component("yl-invoice", {
  template: `
    <span>
        <el-table id="ExportInvoice" :data="data" style="display: none; width: 100%;margin-bottom: 20px;">
        <el-table-column align="center" prop="Enterprise_Name" label="公司信息"></el-table-column>
        <el-table-column align="center" prop="Invoice_Type" label="发票类型"></el-table-column>
        <el-table-column align="center" prop="Invoice_Amount" label="开票金额"></el-table-column>
        <el-table-column align="center" prop="Article_Code" label="史泰博编码"></el-table-column>
        <el-table-column align="center" prop="Article_Name" label="产品详情"></el-table-column>
        <el-table-column align="center" prop="Sales_Unit_Price" label="单价"></el-table-column>
        <el-table-column align="center" prop="Quantity" label="数量"></el-table-column>
        <el-table-column align="center" prop="Reality_Amount" label="合计"></el-table-column>
        <el-table-column align="center" prop="Enterprise_Province" label="省份"></el-table-column>
        <el-table-column align="center" prop="Department_Name" label="公司"></el-table-column>
        <el-table-column align="center" prop="Sales_Contacts" label="联系人"></el-table-column>
        <el-table-column align="center" prop="Sales_Phone" label="联系电话"></el-table-column>
        <el-table-column align="center" prop="Sales_Address" label="邮寄地址"></el-table-column>
        </el-table>
    </span>`,
  props: ["data"],
});
Vue.component("invoice", {
  template: `<el-dialog title="开票" :visible.sync="visibleDialog" width="80vw">
        <yl-invoice :data="invoiceData"></yl-invoice>
        <el-table v-if="tab=='1'" :data="tableData" stripe border height="55vh" style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column align="center" type="selection" :selectable="selectable" width="50"></el-table-column>    
            <el-table-column align="center" type="index" label="序号" width="50"></el-table-column>
            <el-table-column align="center" prop="Article_Name" show-overflow-tooltip label="商品名称"></el-table-column>
            <el-table-column align="center" prop="Sales_Unit_Price" show-overflow-tooltip label="单价"></el-table-column>
            <el-table-column align="center" prop="Quantity" show-overflow-tooltip label="数量"></el-table-column>
            <el-table-column align="center" prop="Amount" show-overflow-tooltip label="总价"></el-table-column>
            <el-table-column align="center" prop="Row_Status" show-overflow-tooltip label="是否开票">
                <template v-slot="{row}">
                    {{row.Row_Status=='0'?'未开票':'已开票'}}
                </template>
            </el-table-column>
        </el-table>
        <el-form v-if="tab=='2'" ref="contract" :model="form" :rules="rules" :inline-message="true">
            <el-descriptions :column="1" border size="small">
                <el-descriptions-item label="公司抬头">
                    <el-form-item prop="Department_Bank_Account_SerialNumber">
                        <el-select @change="change" v-model.trim="form.Department_Bank_Account_SerialNumber" clearable style="width: 100%;" placeholder="请选择付款类型">
                            <el-option v-for="(item,index) in Data" :key="index" :label="item.Enterprise_Name" :value="item.Department_Bank_Account_SerialNumber"></el-option>
                        </el-select>
                    </el-form-item>
                </el-descriptions-item>
                <el-descriptions-item label="发票类型">
                    <el-form-item prop="Invoice_Type">
                        <el-select v-model.trim="form.Invoice_Type" clearable style="width: 100%;" placeholder="请选择发票类型">
                            <el-option v-for="(item,index) in Type" :key="index" :label="item" :value="item"></el-option>
                        </el-select>
                    </el-form-item>
                </el-descriptions-item>
                <el-descriptions-item label="发票号">
                    <el-form-item prop="Invoice_SerialNumber">
                        <el-input v-model="js.Invoice_SerialNumber" placeholder="请输入内容"></el-input>
                    </el-form-item>
                </el-descriptions-item>
            </el-descriptions>
        </el-form> 
        <span slot="footer" class="dialog-footer">
            <el-button @click="$emit('update:visible',false)">取消</el-button>
            <el-button :type="tab=='1'?'primary':''" @click="activeTab">{{tab=='1'?'开票':'返回'}}</el-button>
            <el-button v-if="tab=='2'" type="primary" @click="Export">确定</el-button>
        </span>
    </el-dialog>`,
  props: ["data", "visible"],
  data() {
    return {
      js: {
        Purchase_SerialNumber: "",
        Clearing_SerialNumber: "",
        Invoice_SerialNumber: "",
      },
      visibleDialog: false,
      tableData: [], //详情
      form: {
        Invoice_SerialNumber: "",
        Reconciliation_Invoice_SerialNumber: "",
        Department_Reconciliation_SerialNumber: "",
        Department_Bank_Account_SerialNumber: "",
        Create_Date: "",
        Enterprise_Name: "",
        Enterprise_Province: "",
        Enterprise_City: "",
        Enterprise_County: "",
        Enterprise_Details: "",
        Enterprise_Contacts: "",
        Enterprise_Phone: "",
        Bank_Name: "",
        Account_Number: "",
        Invoice_Type: "",
        Invoice_Amount: 0,
        Children: {
          business_reconciliation_invoice_detail: [],
        },
      },
      Data: [], //可选
      Type: ["电子普票", "专票"], //类型
      rules: {},
      total: 0,
      loading: false,
      tab: "1",
      invoiceData: [],
      multipleSelection: [],
    };
  },
  computed: {
    max() {
      return parseFloat(
        accSub(this.data.Remain_Amount, this.data.Invoice_Amount)
      );
    },
  },
  watch: {
    visible() {
      this.visibleDialog = this.visible;
    },
    visibleDialog(val) {
      this.$emit("update:visible", val);
      if (val) {
        this.form.Invoice_Amount = this.max;
        this.getData(this.data.Department_SerialNumber);
        this.getList(this.data.Department_Reconciliation_SerialNumber);
      }
    },
  },
  methods: {
    handleinvoice(row) {
      console.log(row);

      this.js = row;
    },
    selectable(row) {
      return row.Row_Status == "0";
    },
    handleSelectionChange(val) {
      console.log(val);
      console.log(this.form);

      this.multipleSelection = val;
    },
    //查询开票中的商品列表
    getList(val) {
      const that = this;
      console.log(val);
      // return;
      $.ajax({
        // headers: requestHeaders(),
        // url: `${BASE_URL2}/generalBusiness/generalQueryBySQLSerialNumberWithOriginal`,
        url: "https://service.kdddy.cn/hnx/select/ReconciliationDetail",
        type: "get",
        data: {
          id: val,
          // SQLSerialNumber: "M_business_department_reconciliation_detail",
          // Condition: window.btoa(unescape(encodeURIComponent(val))),
          // ExtensionCondition: "",
        },
        success: function (Result) {
          console.log(Result);

          that.tableData = Result.Data;
        },
        complete: function (XMLHttpRequest) {
          requestPretreatment(XMLHttpRequest);
        },
        dataType: "json",
      });
    },
    getData(Department_SerialNumber) {
      const that = this;
      $.ajax({
        headers: requestHeaders(),
        url: `${BASE_URL2}/generalBusiness/generalQueryByTableName`,
        type: "POST",
        data: {
          Data: "business_department_bank_account",
          Condition:
            "Department_SerialNumber='" + Department_SerialNumber + "'",
        },
        success: function (res) {
          that.Data = res;
        },
        complete: function (XMLHttpRequest) {
          that.loading = false;
          requestPretreatment(XMLHttpRequest);
        },
        dataType: "json",
      });
    },
    activeTab() {
      //开票主体
      if (this.tab == 1) {
        if (this.multipleSelection.length > 0) {
          this.tab = 2;
        } else {
          this.$message({
            type: "warning",
            message: "请选择明细",
          });
        }
      } else {
        this.tab = 1;
      }
    },
    change(e) {
      let obj = this.Data.filter(
        (i) => i.Department_Bank_Account_SerialNumber == e
      )[0];
      this.form = { ...this.form, ...obj };
    },
    Export() {
      let str = this.js.Invoice_SerialNumber//发票号
      const that = this;
      this.form.Department_Reconciliation_SerialNumber =
        this.data.Department_Reconciliation_SerialNumber;
      this.form.Create_Date = getYMDHMSDate();
      this.form.Children.business_reconciliation_invoice_detail = [];
      this.multipleSelection.forEach((item) => {
        item.Row_Status = "1";
        this.invoiceData.push({ ...item, ...this.form });
        this.form.Children.business_reconciliation_invoice_detail.push({
          Reconciliation_Invoice_Detail_SerialNumber: "",
          Reconciliation_Invoice_SerialNumber: "",
          Sales_Order_Detail_SerialNumber: item.Sales_Order_Detail_SerialNumber,
        });
      });
      console.log(this.invoiceData);

      // that.multipleSelection.forEach((item, index) => {
      //   delete item.Operation_Datetime;
      //   delete item.Operation_Datetime_Original;
      // });
      console.log(that.multipleSelection);
      console.log(that.form);
      let Reconciliation_Invoice_SerialNumber = localStorage.getItem(
        "Reconciliation_Invoice_SerialNumber"
      );
      this.js.Reconciliation_Invoice_SerialNumber =
        Reconciliation_Invoice_SerialNumber;
      let lArray = new Array();
      lArray.push(this.js);
      console.log(lArray);
      //500
      $.ajax({
        headers: {
          AccessToken: getCookie("token"),
        },
        contentType: "application/json", // 设置请求体的媒体类型为application/json
        // headers: requestHeaders(),
        url: "https://service.kdddy.cn/hnx/write/Reconciliation",
        type: "POST",
        data: JSON.stringify(lArray),
        success: function (Result) {
          console.log(Result);
          that.form.Invoice_SerialNumber = str;
          $.ajax({
            headers: requestHeaders(),
            url: `${BASE_URL2}/generalBusiness/generalSave`,
            type: "POST",
            data: {
              Data: JSON.stringify({
                Add: { business_reconciliation_invoice: [that.form] },
                Modify: {
                  business_department_reconciliation_detail:
                    that.multipleSelection,
                },
              }),
            },
            success: function (res) {
              if (res.Status == "success") {
                const wb = XLSX.utils.book_new();
                const ws_data1 = [
                  [
                    "订单号",
                    "发货单号",
                    "公司信息",
                    "发票类型",
                    "开票金额",
                    "史泰博编码",
                    "产品详情",
                    "单价",
                    "数量",
                    "合计",
                    "省份",
                    "公司",
                    "联系人",
                    "联系电话",
                    "邮寄地址",
                    "详细地址",
                  ],
                ];
                const ws_data2 = [
                  ["商品名称", "史泰博编码", "数量", "单价", "合计"],
                ];
                that.invoiceData.forEach((item) => {
                  let arr = [
                    item.Sales_Order_SerialNumber,
                    item.Sales_Order_Detail_SerialNumber,
                    item.Enterprise_Name,
                    item.Invoice_Type,
                    item.Invoice_Amount,
                    "",
                    item.Article_Name,
                    item.Sales_Unit_Price,
                    item.Quantity,
                    accMul(item.Sales_Unit_Price, item.Quantity),
                    item.Enterprise_Province,
                    item.Enterprise_Name,
                    item.Sales_Contacts,
                    item.Sales_Phone,
                    item.Sales_Address.split("/")[0] +
                      "-" +
                      item.Sales_Address.split("/")[1] +
                      "-" +
                      item.Sales_Address.split("/")[2],
                    item.Sales_Address.split("/")[3],
                  ];
                  let arr1 = [
                    item.Article_Name,
                    "",
                    item.Quantity,
                    item.Sales_Unit_Price,
                    accMul(item.Sales_Unit_Price, item.Quantity),
                  ];
                  ws_data1.push(arr);
                  ws_data2.push(arr1);
                });
                const ws1 = XLSX.utils.aoa_to_sheet(ws_data1);
                const ws2 = XLSX.utils.aoa_to_sheet(ws_data2);
                let obj = {};
                ws_data1.forEach((item, index) => {
                  if (obj[item[0]]) {
                    obj[item[0]][1] = index;
                  } else {
                    obj[item[0]] = [index, index];
                  }
                });
                ws1["!merges"] = [];
                for (let key in obj) {
                  if (obj[key][0] != obj[key][1]) {
                    ws1["!merges"].push(
                      {
                        s: { c: 0, r: obj[key][0] },
                        e: { c: 0, r: obj[key][1] },
                      },
                      {
                        s: { c: 2, r: obj[key][0] },
                        e: { c: 2, r: obj[key][1] },
                      },
                      {
                        s: { c: 3, r: obj[key][0] },
                        e: { c: 3, r: obj[key][1] },
                      },
                      {
                        s: { c: 10, r: obj[key][0] },
                        e: { c: 10, r: obj[key][1] },
                      },
                      {
                        s: { c: 11, r: obj[key][0] },
                        e: { c: 11, r: obj[key][1] },
                      },
                      {
                        s: { c: 12, r: obj[key][0] },
                        e: { c: 12, r: obj[key][1] },
                      },
                      {
                        s: { c: 13, r: obj[key][0] },
                        e: { c: 13, r: obj[key][1] },
                      },
                      {
                        s: { c: 14, r: obj[key][0] },
                        e: { c: 14, r: obj[key][1] },
                      },
                      {
                        s: { c: 15, r: obj[key][0] },
                        e: { c: 15, r: obj[key][1] },
                      }
                    );
                  }
                }
                ws1["!cols"] = [];

                ws_data1[0].forEach((item) => {
                  ws1["!cols"].push({
                    alignment: { horizontal: "center" },
                    wpx: 150,
                  });
                });
                ws2["!cols"] = [];
                ws_data2[0].forEach((item) => {
                  ws2["!cols"].push({
                    alignment: { horizontal: "center" },
                    wpx: 150,
                  });
                });
                XLSX.utils.book_append_sheet(wb, ws1, "对账明细");
                XLSX.utils.book_append_sheet(wb, ws2, "对账汇总");
                XLSX.writeFile(wb, "开票导出" + +new Date() + ".xlsx");
              } else {
                that.$message.error("操作失败，请稍后再试");
              }
            },
            complete: function (XMLHttpRequest) {
              that.loading = false;
              that.$message({
                message: "恭喜你，开票及对账单下载完成",
                type: "success",
              });
              that.visibleDialog = false;

              requestPretreatment(XMLHttpRequest); //config/config.js 响应预检
            },
            dataType: "json",
          });
        },
        complete: function (XMLHttpRequest) {
          requestPretreatment(XMLHttpRequest); //config/config.js 响应预检
        },
        dataType: "json",
      });
    },
  },
});
Vue.component("show-detail", {
  template: `<el-dialog title="明细查询" :visible.sync="visibleDialog" width="80vw">
    <el-tabs v-model="activeName">
        <el-tab-pane label="明细查询" name="1">
            <el-table :data="tableData" stripe border min-height="50vh" style="width: 100%">
            <el-table-column align="center" type="index" label="序号" width="50"></el-table-column>
            <el-table-column align="center" prop="Sales_Order_Detail_SerialNumber" width="200" show-overflow-tooltip label="销售订单明细"></el-table-column>
            <el-table-column align="center" prop="Member_Name" show-overflow-tooltip label="下单人"></el-table-column>
            <el-table-column align="center" prop="Supplier_Name" show-overflow-tooltip label="供应商名称"></el-table-column>
            <el-table-column align="center" prop="Article_Name" show-overflow-tooltip label="商品名称"></el-table-column>
            <el-table-column align="center" prop="Specifications_Name" show-overflow-tooltip label="规格名称"></el-table-column>
            <el-table-column align="center" prop="Quantity" show-overflow-tooltip label="购买数量"></el-table-column>
            <el-table-column align="center" prop="Sales_Unit_Price" show-overflow-tooltip label="销售单价"></el-table-column>
            <el-table-column align="center" prop="Amount" show-overflow-tooltip label="销售总价"></el-table-column>
            <el-table-column align="center" prop="Reality_Amount" show-overflow-tooltip label="实际收款"></el-table-column>
            <el-table-column align="center" prop="Sales_Point" show-overflow-tooltip label="消费积分"></el-table-column>
            <el-table-column align="center" prop="Activity_Name" show-overflow-tooltip label="参与活动"></el-table-column>
            <el-table-column align="center" prop="Sales_Contacts" show-overflow-tooltip label="收货人"></el-table-column>
            <el-table-column align="center" prop="Sales_Phone" show-overflow-tooltip label="收货人联系方式"></el-table-column>
            </el-table>
            <el-pagination style="margin-top: 5px;" background @size-change="handleSizeChange"
            @current-change="handleCurrentChange" :current-page="form.page" :page-sizes="[10, 20, 30, 50, 100, 500]"
            :page-size="form.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </el-tab-pane>
        <el-tab-pane label="开票记录" name="2">
            <yl-invoice :data="invoice"></yl-invoice>
            <el-table :data="invoiceData" stripe border min-height="50vh" style="width: 100%" @expand-change="expandChange">
                <el-table-column align="center" type="expand" width="50">
                    <template slot-scope="{row}">
                        <el-table :data="row.Children.detail" stripe border style="width: 100%"> 
                            <el-table-column align="center" type="index" label="序号" width="50"></el-table-column>
                            <el-table-column align="center" prop="Sales_Order_Detail_SerialNumber" show-overflow-tooltip label="订单明细"></el-table-column>
                            <el-table-column align="center" prop="Article_Name" show-overflow-tooltip label="商品名称"></el-table-column>
                            <el-table-column align="center" prop="Specifications_Name" show-overflow-tooltip label="规格名称"></el-table-column>
                            <el-table-column align="center" prop="Sales_Unit_Price" show-overflow-tooltip label="单价"></el-table-column>
                            <el-table-column align="center" prop="Quantity" show-overflow-tooltip label="数量"></el-table-column>
                            <el-table-column align="center" prop="Amount" show-overflow-tooltip label="总价"></el-table-column>
                        </el-table>
                    </template>
                </el-table-column>
                <el-table-column align="center" type="index" label="序号" width="50"></el-table-column>
                <el-table-column align="center" prop="Reconciliation_Invoice_SerialNumber" width="200" show-overflow-tooltip label="日志流水号"></el-table-column>
                <el-table-column align="center" prop="Enterprise_Name" show-overflow-tooltip label="公司信息"></el-table-column>
                <el-table-column align="center" prop="Invoice_Type" show-overflow-tooltip label="发票类型"></el-table-column>
                <el-table-column align="center" prop="Invoice_Amount" show-overflow-tooltip label="开票金额"></el-table-column>
                <el-table-column align="center" prop="Create_Date" show-overflow-tooltip label="开票时间"></el-table-column>
                <el-table-column align="center" prop="Enterprise_Province" show-overflow-tooltip label="省份"></el-table-column>
                <el-table-column align="center" label="操作" width="160">
                    <template v-slot="{row}">
                        <el-button type="primary" size="small" @click="download(row.Reconciliation_Invoice_SerialNumber)">下载</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-tab-pane>
    </el-tabs>   
    <span slot="footer" class="dialog-footer">
        <el-button @click="$emit('update:visible',false)">返回</el-button>
    </span></el-dialog>`,
  props: ["id", "visible"],
  data() {
    return {
      visibleDialog: false,
      refreshDialog: false,
      tableData: [],
      invoiceData: [],
      form: {
        SQLSerialNumber: "P_business_department_reconciliation_detail",
        PaginationNumber: 1,
        RowAmount: 10,
        ExtensionCondition: "",
        Condition: "",
      },
      total: 0,
      activeName: "1",
      invoice: [],
    };
  },
  watch: {
    visible() {
      this.visibleDialog = this.visible;
    },
    visibleDialog(val) {
      this.$emit("update:visible", val);
      if (val) {
        this.form.Condition = window.btoa(
          unescape(encodeURIComponent(this.id))
        );
        console.log(this.id);
        this.getList(this.form);
        this.getData(this.id);
      }
    },
  },
  methods: {
    handleSizeChange(val) {
      this.form.PaginationNumber = 1;
      this.form.RowAmount = val;
      this.getList(this.form);
    },
    handleCurrentChange(val) {
      console.log(val);

      this.form.PaginationNumber = val;
      this.getList(this.form);
    },
    expandChange(row) {
      //展开
      const that = this;
      $.ajax({
        headers: requestHeaders(),
        url: `${BASE_URL2}/generalBusiness/generalQueryBySQLSerialNumber`,
        type: "POST",
        data: {
          SQLSerialNumber: "A_business_reconciliation_invoice_detail",
          Condition: window.btoa(
            unescape(
              encodeURIComponent(row.Reconciliation_Invoice_SerialNumber)
            )
          ),
          ExtensionCondition: "",
        },
        success: function (Result) {
          row.Children.detail = Result;
        },
        complete: function (XMLHttpRequest) {
          that.refreshDialog = false;
          requestPretreatment(XMLHttpRequest);
        },
        dataType: "json",
      });
    },
    getList(data) {
      const that = this;
      $.ajax({
        headers: requestHeaders(),
        url: `${BASE_URL2}/generalBusiness/generalPaginationQueryBySQLSerialNumber`,
        type: "POST",
        data,
        success: function (Result) {
          that.tableData = Result.Rows;
          that.total = Result.TotalRows;
        },
        complete: function (XMLHttpRequest) {
          that.refreshDialog = false;
          requestPretreatment(XMLHttpRequest);
        },
        dataType: "json",
      });
    },
    getData(id) {
      const that = this;
      $.ajax({
        headers: requestHeaders(),
        url: `${BASE_URL2}/generalBusiness/generalQueryBySQLSerialNumber`,
        type: "POST",
        data: {
          SQLSerialNumber: "A_business_reconciliation_invoice",
          Condition: window.btoa(unescape(encodeURIComponent(id))),
          ExtensionCondition: "",
        },
        success: function (Result) {
          Result.forEach((item) => {
            item.Children = {
              detail: [],
            };
          });
          that.invoiceData = Result;
        },
        complete: function (XMLHttpRequest) {
          requestPretreatment(XMLHttpRequest);
        },
        dataType: "json",
      });
    },
    download(id) {
      const that = this;
      $.ajax({
        headers: requestHeaders(),
        url: `${BASE_URL2}/generalBusiness/generalQueryBySQLSerialNumber`,
        type: "POST",
        data: {
          SQLSerialNumber: "M_business_reconciliation_invoice",
          Condition: window.btoa(unescape(encodeURIComponent(id))),
          ExtensionCondition: "",
        },
        success: function (Result) {
          that.invoice = Result;
          const wb = XLSX.utils.book_new();
          const ws_data1 = [
            [
              "订单号",
              "发货单号",
              "公司信息",
              "发票类型",
              "开票金额",
              "史泰博编码",
              "产品详情",
              "单价",
              "数量",
              "合计",
              "省份",
              "公司",
              "联系人",
              "联系电话",
              "邮寄地址",
              "详细地址",
            ],
          ];
          const ws_data2 = [["商品名称", "史泰博编码", "数量", "单价", "合计"]];
          Result.forEach((item) => {
            let arr = [
              item.Sales_Order_SerialNumber,
              item.Sales_Order_Detail_SerialNumber,
              item.Enterprise_Name,
              item.Invoice_Type,
              item.Invoice_Amount,
              "",
              item.Article_Name,
              item.Sales_Unit_Price,
              item.Quantity,
              accMul(item.Sales_Unit_Price, item.Quantity),
              item.Enterprise_Province,
              item.Enterprise_Name,
              item.Sales_Contacts,
              item.Sales_Phone,
              item.Sales_Address.split("/")[0] +
                "-" +
                item.Sales_Address.split("/")[1] +
                "-" +
                item.Sales_Address.split("/")[2],
              item.Sales_Address.split("/")[3],
            ];
            let arr1 = [
              item.Article_Name,
              "",
              item.Quantity,
              item.Sales_Unit_Price,
              accMul(item.Sales_Unit_Price, item.Quantity),
            ];
            ws_data1.push(arr);
            ws_data2.push(arr1);
          });
          const ws1 = XLSX.utils.aoa_to_sheet(ws_data1);
          const ws2 = XLSX.utils.aoa_to_sheet(ws_data2);
          let obj = {};
          ws_data1.forEach((item, index) => {
            if (obj[item[0]]) {
              obj[item[0]][1] = index;
            } else {
              obj[item[0]] = [index, index];
            }
          });
          ws1["!merges"] = [];
          for (let key in obj) {
            if (obj[key][0] != obj[key][1]) {
              ws1["!merges"].push(
                {
                  s: { c: 0, r: obj[key][0] },
                  e: { c: 0, r: obj[key][1] },
                },
                {
                  s: { c: 2, r: obj[key][0] },
                  e: { c: 2, r: obj[key][1] },
                },
                {
                  s: { c: 3, r: obj[key][0] },
                  e: { c: 3, r: obj[key][1] },
                },
                {
                  s: { c: 10, r: obj[key][0] },
                  e: { c: 10, r: obj[key][1] },
                },
                {
                  s: { c: 11, r: obj[key][0] },
                  e: { c: 11, r: obj[key][1] },
                },
                {
                  s: { c: 12, r: obj[key][0] },
                  e: { c: 12, r: obj[key][1] },
                },
                {
                  s: { c: 13, r: obj[key][0] },
                  e: { c: 13, r: obj[key][1] },
                },
                {
                  s: { c: 14, r: obj[key][0] },
                  e: { c: 14, r: obj[key][1] },
                },
                {
                  s: { c: 15, r: obj[key][0] },
                  e: { c: 15, r: obj[key][1] },
                }
              );
            }
          }
          ws1["!cols"] = [];
          ws_data1[0].forEach((item) => {
            ws1["!cols"].push({
              alignment: { horizontal: "center" },
              wpx: 150,
            });
          });
          ws2["!cols"] = [];
          ws_data2[0].forEach((item) => {
            ws2["!cols"].push({
              alignment: { horizontal: "center" },
              wpx: 150,
            });
          });
          XLSX.utils.book_append_sheet(wb, ws1, "对账明细");
          XLSX.utils.book_append_sheet(wb, ws2, "对账汇总");
          XLSX.writeFile(wb, "开票导出" + +new Date() + ".xlsx");
          that.$emit("update:visible", false);
        },
        complete: function (XMLHttpRequest) {
          requestPretreatment(XMLHttpRequest);
        },
        dataType: "json",
      });
    },
  },
});
new Vue({
  el: "#app",
  data() {
    return {
      a: false,
      js: {
        Purchase_SerialNumber: "",
        Clearing_SerialNumber: "",
        Invoice_SerialNumber: "",
      },
      dialogFormVisible: false,
      formLabelWidth: "120px",
      form: {
        SQLSerialNumber: "P_business_department_reconciliation", //与甲方对账
        PaginationNumber: 1, //页数
        RowAmount: 20, //每页数据条数
        Condition: "",
        ExtensionCondition: "",
        Article_Name: "",
        Member_Name: "",
        Member_SerialNumber: "",
        Sales_Order_SerialNumber: "",
        Activity_Name: "",
        Sales_Date: null,
        Reconciliation_Name: "",
        Reconciliation_People: "",
        clerk: "",
        page:1,
        limit:10,
      },
      total: 0,
      tableData: [], //表格数据
      ExportData: [], //导出
      loading: false,
      dialogInvoiceVisible: false,
      dialogVisible: false,
      Department_Reconciliation_SerialNumber: "",
      data: {},
    };
  },
  mounted() {
    this.getList(this.form); //前端分页
  },
  methods: {
    filterTag1(value, row) {
      console.log(value, row);

      return row.Receipts_Status === value;
    },
    jsqd() {
      console.log(this.js);
      this.dialogFormVisible = false;
      let lArray = new Array();
      lArray.push(this.js);
      console.log(lArray);

      $.ajax({
        headers: {
          AccessToken: getCookie("token"),
        },
        contentType: "application/json", // 设置请求体的媒体类型为application/json
        url: "https://service.kdddy.cn/hnx/write/Reconciliation",
        type: "POST",
        data: JSON.stringify(lArray),
        success: function (Result) {
          console.log(Result);
          // if (Result.Status === "success") {
          //   _this.$message.success("提交成功");
          //   window.history.go(-1);
          // } else {
          //   _this.$message.error("提交失败，请稍后再试");
          // }
        },
        complete: function (XMLHttpRequest) {
          requestPretreatment(XMLHttpRequest); //config/config.js 响应预检
        },
        dataType: "json",
      });
    },
    jsd(row) {
      console.log(row);
      this.js = row;
      this.dialogFormVisible = true;
    },
    filterTag(value, row) {
      console.log(value, row);

      return row.KP_Status === value;
    },
    onSerach() {
      //查询方法
      this.form.PaginationNumber = 1;
      this.getList(this.form);
    },
    handleSizeChange(val) {
      this.page = 1;
      this.form.limit = val;
      // this.form.PaginationNumber = 1;
      // this.form.RowAmount = val;
      // this.getList(this.form);
    },
    handleCurrentChange(val) {
      this.form.page = val
      // this.form.PaginationNumber = val;
      // this.getList(this.form);
    },
    Add() {
      window.location.href = "./add.html";
    },
    getList(form) {
      //换页方法
      const that = this;
      console.log(this.form.Sales_Date);
      // let start = this.form.Sales_Date[0];
      // let end = this.form.Sales_Date[1];
      console.log(this.form.Reconciliation_Name);
      console.log(this.form.Reconciliation_People);
      console.log(this.form.clerk);

      console.log(this.form);
      //   let data = deepClone(form);
      //   return;
      $.ajax({
        // headers: requestHeaders(),
        headers: {
          AccessToken: getCookie("token"),
        },
        type: "POST",
        contentType: "application/json", // 设置请求体的媒体类型为application/json
        // url: `${BASE_URL2}/generalBusiness/generalPaginationQueryBySQLSerialNumber`,
        // url: "https://service.kdddy.cn/hnx/select/Reconciliation",
        //500
        url: "https://service.kdddy.cn/hnx/select/Reconciliation",
        data: JSON.stringify([
          {
            start: "", //表名
            end: "",
            Reconciliation_Name: "",
            Reconciliation_People: "",
            Clerk: "",
            pageSize: 100,
            offset: 1,
          },
        ]),
        success: function (Result) {
          console.log(Result);
          that.tableData = Result.Data;
          that.total = Result.total;
        },
        complete: function (XMLHttpRequest) {
          //   requestPretreatment(XMLHttpRequest);
        },
        dataType: "json",
      });
      // data.Condition = window.btoa(unescape(encodeURIComponent("%" + data.Member_Name  + "%,%"+ data.Member_SerialNumber  +"%,%"+data.Sales_Order_SerialNumber +"%,%"+data.Activity_Name +"%,%"+data.Article_Name +"%")))
      // let sql = "";
      // if (data.Sales_Date) {
      //     sql = sql + "AND business_sales_order.Sales_Date BETWEEN '" + data.Sales_Date[0] + "' AND '" + data.Sales_Date[1] + "'\r\n"
      // }
      // data.ExtensionCondition = window.btoa(unescape(encodeURIComponent(sql)));
      //   $.ajax({
      //     headers: requestHeaders(),
      //     url: `${BASE_URL2}/generalBusiness/generalPaginationQueryBySQLSerialNumber`,
      //     type: "POST",
      //     data,
      //     success: function (Result) {
      //       that.tableData = Result.Rows;
      //       that.total = Result.TotalRows;
      //       console.log(Result.Rows);
      //     },
      //     complete: function (XMLHttpRequest) {
      //       requestPretreatment(XMLHttpRequest);
      //     },
      //     dataType: "json",
      //   });
    },
    Show(Department_Reconciliation_SerialNumber) {
      this.Department_Reconciliation_SerialNumber =
        Department_Reconciliation_SerialNumber;
      this.dialogVisible = true;
    },
    Export(form) {
      // console.log(form);

      //导出
      const that = this;
      this.loading = true;
      let data = deepClone(form);
      // data.Condition = window.btoa(unescape(encodeURIComponent("%" + data.Member_Name + "%,%" + data.Member_SerialNumber + "%,%" + data.Sales_Order_SerialNumber + "%,%" + data.Activity_Name + "%,%" + data.Article_Name + "%")))
      let sql = "";
      // if (data.Sales_Date) {
      //     sql = sql + "AND business_sales_order.Sales_Date BETWEEN '" + data.Sales_Date[0] + "' AND '" + data.Sales_Date[1] + "'\r\n"
      // }
      data.ExtensionCondition = window.btoa(unescape(encodeURIComponent(sql)));
      $.ajax({
        headers: requestHeaders(),
        url: `${BASE_URL2}/generalBusiness/generalQueryBySQLSerialNumber`,
        type: "POST",
        data,
        success: function (Result) {
          if (Result.length > 0) {
            that.ExportData = Result;
            that.$nextTick(() => {
              let wb = XLSX.utils.table_to_book(
                document.querySelector("#ExportData")
              );
              var wbout = XLSX.write(wb, {
                bookType: "xlsx",
                bookSST: true,
                type: "array",
              });
              try {
                saveAs(
                  new Blob([wbout], {
                    type: "application/octet-stream",
                  }),
                  "销售对账表" + +new Date() + ".xlsx"
                );
              } catch (e) {
                if (typeof console !== "undefined") console.log(e, wbout);
              }
              that.$message({
                message: "已成功导出",
                type: "success",
              });
              return wbout;
            });
          } else {
            that.$message({
              message: "暂无可导出的数据",
              type: "warning",
            });
          }
        },
        complete: function (XMLHttpRequest) {
          that.loading = false;
          requestPretreatment(XMLHttpRequest);
        },
        dataType: "json",
      });
    },
    handleinvoice(data) {
      console.log(data);
      this.js = data;
      console.log(this.js);
      localStorage.setItem(
        "Reconciliation_Invoice_SerialNumber",
        this.js.Reconciliation_Invoice_SerialNumber
      );
      this.data = data;
      this.dialogInvoiceVisible = true;
    },
  },
});
